package xyz.esion.knowledgebase.config

import cn.hutool.core.util.StrUtil
import cn.hutool.json.JSONUtil
import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletResponse
import org.springframework.context.annotation.Configuration
import org.springframework.web.servlet.HandlerInterceptor
import org.springframework.web.servlet.config.annotation.InterceptorRegistry
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer
import xyz.esion.knowledgebase.component.R
import xyz.esion.knowledgebase.properties.ConfigProperties

/**
 * @author Esion
 * @since 2024/1/23
 */
@Configuration
class WebConfig(private val properties: ConfigProperties) : WebMvcConfigurer {

    override fun addInterceptors(registry: InterceptorRegistry) {
        registry.addInterceptor(object : HandlerInterceptor {
            override fun preHandle(request: HttpServletRequest, response: HttpServletResponse, handler: Any): Boolean {
                // token拦截
                val token = request.getHeader("token")
                val success =  StrUtil.nullToDefault(properties.token, "") == StrUtil.nullToDefault(token, "")
                if (!success) {
                    // 不相等，直接返回异常
                    response.writer.println(JSONUtil.toJsonStr(R.noAuth()))
                    response.status = 401
                }
                return success
            }
        }).addPathPatterns("/api/**")
    }

}